/**
 * 脚本用于更新所有设计模式的示例代码为Java代码
 */
const mongoose = require('mongoose');
const config = require('config');
const Pattern = require('../models/Pattern');

// 连接数据库
const db = config.get('mongoURI');

mongoose.connect(db, {
  useNewUrlParser: true,
  useUnifiedTopology: true
}).then(() => {
  console.log('MongoDB 连接成功');
  updatePatternSampleCodes();
}).catch(err => {
  console.error('MongoDB 连接失败', err.message);
  process.exit(1);
});

// 设计模式Java示例代码
const patternSampleCodes = {
  // 创建型模式
  'Singleton': `/**
 * 单例模式示例
 */
public class Singleton {
    // 私有静态实例
    private static Singleton instance;
    
    // 私有构造函数，防止外部实例化
    private Singleton() {
        // 初始化操作
    }
    
    // 公共静态方法提供全局访问点
    public static synchronized Singleton getInstance() {
        // 懒加载
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
    
    // 业务方法
    public void doSomething() {
        System.out.println("Singleton is doing something...");
    }
}

// 客户端代码
public class Client {
    public static void main(String[] args) {
        // 获取单例实例
        Singleton singleton1 = Singleton.getInstance();
        Singleton singleton2 = Singleton.getInstance();
        
        // 验证两个引用指向同一对象
        System.out.println("是否是同一个实例: " + (singleton1 == singleton2));
        
        // 使用单例
        singleton1.doSomething();
    }
}`,

  'Factory Method': `/**
 * 工厂方法模式示例
 */
// 产品接口
interface Product {
    void operation();
}

// 具体产品A
class ConcreteProductA implements Product {
    @Override
    public void operation() {
        System.out.println("ConcreteProductA operation");
    }
}

// 具体产品B
class ConcreteProductB implements Product {
    @Override
    public void operation() {
        System.out.println("ConcreteProductB operation");
    }
}

// 创建者抽象类
abstract class Creator {
    // 工厂方法
    public abstract Product createProduct();
    
    // 使用产品的方法
    public void someOperation() {
        // 调用工厂方法创建产品
        Product product = createProduct();
        // 使用产品
        product.operation();
    }
}

// 具体创建者A
class ConcreteCreatorA extends Creator {
    @Override
    public Product createProduct() {
        return new ConcreteProductA();
    }
}

// 具体创建者B
class ConcreteCreatorB extends Creator {
    @Override
    public Product createProduct() {
        return new ConcreteProductB();
    }
}

// 客户端代码
public class Client {
    public static void main(String[] args) {
        // 使用ConcreteCreatorA
        Creator creatorA = new ConcreteCreatorA();
        creatorA.someOperation(); // 输出: ConcreteProductA operation
        
        // 使用ConcreteCreatorB
        Creator creatorB = new ConcreteCreatorB();
        creatorB.someOperation(); // 输出: ConcreteProductB operation
    }
}`,

  'Abstract Factory': `/**
 * 抽象工厂模式示例
 */
// 抽象产品A
interface AbstractProductA {
    void operationA();
}

// 抽象产品B
interface AbstractProductB {
    void operationB();
    // 与产品A协作的方法
    void collaborateWithA(AbstractProductA productA);
}

// 具体产品A1
class ConcreteProductA1 implements AbstractProductA {
    @Override
    public void operationA() {
        System.out.println("Product A1 operation");
    }
}

// 具体产品A2
class ConcreteProductA2 implements AbstractProductA {
    @Override
    public void operationA() {
        System.out.println("Product A2 operation");
    }
}

// 具体产品B1
class ConcreteProductB1 implements AbstractProductB {
    @Override
    public void operationB() {
        System.out.println("Product B1 operation");
    }
    
    @Override
    public void collaborateWithA(AbstractProductA productA) {
        System.out.println("Product B1 collaborating with " + productA.getClass().getSimpleName());
    }
}

// 具体产品B2
class ConcreteProductB2 implements AbstractProductB {
    @Override
    public void operationB() {
        System.out.println("Product B2 operation");
    }
    
    @Override
    public void collaborateWithA(AbstractProductA productA) {
        System.out.println("Product B2 collaborating with " + productA.getClass().getSimpleName());
    }
}

// 抽象工厂
interface AbstractFactory {
    AbstractProductA createProductA();
    AbstractProductB createProductB();
}

// 具体工厂1 - 创建产品A1和B1
class ConcreteFactory1 implements AbstractFactory {
    @Override
    public AbstractProductA createProductA() {
        return new ConcreteProductA1();
    }
    
    @Override
    public AbstractProductB createProductB() {
        return new ConcreteProductB1();
    }
}

// 具体工厂2 - 创建产品A2和B2
class ConcreteFactory2 implements AbstractFactory {
    @Override
    public AbstractProductA createProductA() {
        return new ConcreteProductA2();
    }
    
    @Override
    public AbstractProductB createProductB() {
        return new ConcreteProductB2();
    }
}

// 客户端代码
public class Client {
    public static void main(String[] args) {
        // 使用工厂1
        AbstractFactory factory1 = new ConcreteFactory1();
        AbstractProductA productA1 = factory1.createProductA();
        AbstractProductB productB1 = factory1.createProductB();
        
        productA1.operationA();
        productB1.operationB();
        productB1.collaborateWithA(productA1);
        
        // 使用工厂2
        AbstractFactory factory2 = new ConcreteFactory2();
        AbstractProductA productA2 = factory2.createProductA();
        AbstractProductB productB2 = factory2.createProductB();
        
        productA2.operationA();
        productB2.operationB();
        productB2.collaborateWithA(productA2);
    }
}`,

  'Builder': `/**
 * 建造者模式示例
 */
// 产品类
class Product {
    private String partA;
    private String partB;
    private String partC;
    
    public void setPartA(String partA) {
        this.partA = partA;
    }
    
    public void setPartB(String partB) {
        this.partB = partB;
    }
    
    public void setPartC(String partC) {
        this.partC = partC;
    }
    
    @Override
    public String toString() {
        return "Product{" +
                "partA='" + partA + '\'' +
                ", partB='" + partB + '\'' +
                ", partC='" + partC + '\'' +
                '}';
    }
}

// 抽象建造者
interface Builder {
    void buildPartA();
    void buildPartB();
    void buildPartC();
    Product getResult();
}

// 具体建造者1
class ConcreteBuilder1 implements Builder {
    private Product product = new Product();
    
    @Override
    public void buildPartA() {
        product.setPartA("Part A for Type 1");
    }
    
    @Override
    public void buildPartB() {
        product.setPartB("Part B for Type 1");
    }
    
    @Override
    public void buildPartC() {
        product.setPartC("Part C for Type 1");
    }
    
    @Override
    public Product getResult() {
        return product;
    }
}

// 具体建造者2
class ConcreteBuilder2 implements Builder {
    private Product product = new Product();
    
    @Override
    public void buildPartA() {
        product.setPartA("Part A for Type 2");
    }
    
    @Override
    public void buildPartB() {
        product.setPartB("Part B for Type 2");
    }
    
    @Override
    public void buildPartC() {
        product.setPartC("Part C for Type 2");
    }
    
    @Override
    public Product getResult() {
        return product;
    }
}

// 指挥者
class Director {
    public void construct(Builder builder) {
        builder.buildPartA();
        builder.buildPartB();
        builder.buildPartC();
    }
}

// 客户端代码
public class Client {
    public static void main(String[] args) {
        Director director = new Director();
        
        // 使用具体建造者1
        ConcreteBuilder1 builder1 = new ConcreteBuilder1();
        director.construct(builder1);
        Product product1 = builder1.getResult();
        System.out.println("Product 1: " + product1);
        
        // 使用具体建造者2
        ConcreteBuilder2 builder2 = new ConcreteBuilder2();
        director.construct(builder2);
        Product product2 = builder2.getResult();
        System.out.println("Product 2: " + product2);
    }
}`,

  'Prototype': `/**
 * 原型模式示例
 */
import java.util.HashMap;
import java.util.Map;

// 原型接口
interface Prototype extends Cloneable {
    Prototype clone();
    void execute();
}

// 具体原型A
class ConcretePrototypeA implements Prototype {
    private String state;
    
    public ConcretePrototypeA(String state) {
        this.state = state;
    }
    
    @Override
    public Prototype clone() {
        try {
            return (Prototype) super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
            return null;
        }
    }
    
    @Override
    public void execute() {
        System.out.println("Executing ConcretePrototypeA with state: " + state);
    }
    
    public void setState(String state) {
        this.state = state;
    }
    
    public String getState() {
        return state;
    }
}

// 具体原型B
class ConcretePrototypeB implements Prototype {
    private int state;
    
    public ConcretePrototypeB(int state) {
        this.state = state;
    }
    
    @Override
    public Prototype clone() {
        try {
            return (Prototype) super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
            return null;
        }
    }
    
    @Override
    public void execute() {
        System.out.println("Executing ConcretePrototypeB with state: " + state);
    }
    
    public void setState(int state) {
        this.state = state;
    }
    
    public int getState() {
        return state;
    }
}

// 原型管理器
class PrototypeManager {
    private Map<String, Prototype> prototypes = new HashMap<>();
    
    public void addPrototype(String key, Prototype prototype) {
        prototypes.put(key, prototype);
    }
    
    public Prototype getPrototype(String key) {
        Prototype prototype = prototypes.get(key);
        if (prototype != null) {
            return prototype.clone();
        }
        return null;
    }
}

// 客户端代码
public class Client {
    public static void main(String[] args) {
        // 创建原型管理器
        PrototypeManager manager = new PrototypeManager();
        
        // 注册原型
        manager.addPrototype("prototypeA", new ConcretePrototypeA("Original State A"));
        manager.addPrototype("prototypeB", new ConcretePrototypeB(100));
        
        // 克隆原型A并使用
        ConcretePrototypeA clonedA = (ConcretePrototypeA) manager.getPrototype("prototypeA");
        clonedA.setState("Modified State A");
        clonedA.execute();
        
        // 克隆原型B并使用
        ConcretePrototypeB clonedB = (ConcretePrototypeB) manager.getPrototype("prototypeB");
        clonedB.setState(200);
        clonedB.execute();
    }
}`,

  // 结构型设计模式
  'Adapter': `/**
 * 适配器模式示例
 */
// 目标接口
interface Target {
    void request();
}

// 被适配者
class Adaptee {
    public void specificRequest() {
        System.out.println("Adaptee's specific request");
    }
}

// 类适配器 (通过继承)
class ClassAdapter extends Adaptee implements Target {
    @Override
    public void request() {
        System.out.println("ClassAdapter: Converting request to specificRequest");
        specificRequest();
    }
}

// 对象适配器 (通过组合)
class ObjectAdapter implements Target {
    private Adaptee adaptee;
    
    public ObjectAdapter(Adaptee adaptee) {
        this.adaptee = adaptee;
    }
    
    @Override
    public void request() {
        System.out.println("ObjectAdapter: Converting request to specificRequest");
        adaptee.specificRequest();
    }
}

// 客户端代码
public class Client {
    public static void main(String[] args) {
        // 使用类适配器
        Target targetWithClassAdapter = new ClassAdapter();
        targetWithClassAdapter.request();
        
        System.out.println("------------------------");
        
        // 使用对象适配器
        Adaptee adaptee = new Adaptee();
        Target targetWithObjectAdapter = new ObjectAdapter(adaptee);
        targetWithObjectAdapter.request();
    }
}`,

  'Bridge': `/**
 * 桥接模式示例
 */
// 实现部分接口
interface Implementor {
    void operationImpl();
}

// 具体实现A
class ConcreteImplementorA implements Implementor {
    @Override
    public void operationImpl() {
        System.out.println("ConcreteImplementorA: Operation implementation");
    }
}

// 具体实现B
class ConcreteImplementorB implements Implementor {
    @Override
    public void operationImpl() {
        System.out.println("ConcreteImplementorB: Operation implementation");
    }
}

// 抽象部分
abstract class Abstraction {
    protected Implementor implementor;
    
    public Abstraction(Implementor implementor) {
        this.implementor = implementor;
    }
    
    public void setImplementor(Implementor implementor) {
        this.implementor = implementor;
    }
    
    public abstract void operation();
}

// 扩展抽象部分
class RefinedAbstraction extends Abstraction {
    public RefinedAbstraction(Implementor implementor) {
        super(implementor);
    }
    
    @Override
    public void operation() {
        System.out.println("RefinedAbstraction: Refined operation");
        implementor.operationImpl();
    }
    
    public void additionalOperation() {
        System.out.println("RefinedAbstraction: Additional operation");
    }
}

// 客户端代码
public class Client {
    public static void main(String[] args) {
        // 创建具体实现
        Implementor implementorA = new ConcreteImplementorA();
        Implementor implementorB = new ConcreteImplementorB();
        
        // 创建抽象部分并关联实现
        Abstraction abstraction = new RefinedAbstraction(implementorA);
        abstraction.operation();
        
        System.out.println("------------------------");
        
        // 切换实现
        abstraction.setImplementor(implementorB);
        abstraction.operation();
        
        System.out.println("------------------------");
        
        // 使用扩展方法
        RefinedAbstraction refinedAbstraction = (RefinedAbstraction) abstraction;
        refinedAbstraction.additionalOperation();
    }
}`
};

// 其他模式代码将在后续添加

async function updatePatternSampleCodes() {
  try {
    const patterns = await Pattern.find();
    let updatedCount = 0;
    
    for (const pattern of patterns) {
      if (patternSampleCodes[pattern.name]) {
        pattern.sampleCode = patternSampleCodes[pattern.name];
        await pattern.save();
        updatedCount++;
        console.log(`更新了 ${pattern.name} 的示例代码`);
      } else {
        console.log(`未找到 ${pattern.name} 的示例代码`);
      }
    }
    
    console.log(`完成更新，共更新了 ${updatedCount} 个模式的示例代码`);
    process.exit(0);
  } catch (err) {
    console.error('更新示例代码失败:', err);
    process.exit(1);
  }
} 